package com.javaee.wordtree.controller;

import com.javaee.wordtree.common.Result;
import com.javaee.wordtree.entity.ModelChat;
import com.javaee.wordtree.service.ModelChatService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 模型聊天控制器
 */
@RestController
@RequestMapping("/model-chats")
public class ModelChatController {

    @Resource
    private ModelChatService modelChatService;

    /**
     * 获取用户的聊天列表
     * 
     * @return 聊天列表
     */
    @GetMapping
    public Result<?> getUserChats(
            @RequestParam(value = "type", required = false) String chatType,
            HttpServletRequest request) {
        String userId = getCurrentUserId(request);
        List<ModelChat> chats;

        if (chatType != null && !chatType.isEmpty()) {
            chats = modelChatService.getUserChatsByType(userId, chatType);
        } else {
            chats = modelChatService.getUserChats(userId);
        }

        return Result.success(chats);
    }

    /**
     * 创建新的聊天会话
     * 
     * @param params 请求参数
     * @return 创建的聊天会话
     */
    @PostMapping
    public Result<?> createChat(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String userId = getCurrentUserId(request);
        String title = params.getOrDefault("title", "新的会话");
        String chatType = params.getOrDefault("type", "english");
        String difficulty = params.getOrDefault("difficulty", "medium");
        String keywords = params.getOrDefault("keywords", "");

        ModelChat chat = modelChatService.createChat(userId, title, chatType, difficulty, keywords);
        return Result.success(chat);
    }

    /**
     * 更新聊天标题或设置
     * 
     * @param chatId 聊天ID
     * @param params 请求参数
     * @return 操作结果
     */
    @PutMapping("/{chatId}")
    public Result<?> updateChat(@PathVariable Integer chatId,
            @RequestBody Map<String, String> params,
            HttpServletRequest request) {
        String userId = getCurrentUserId(request);

        // 检查聊天是否属于当前用户
        if (!modelChatService.isChatBelongToUser(chatId, userId)) {
            return Result.error("-1", "没有权限操作此聊天记录");
        }

        // 获取当前聊天
        ModelChat chat = modelChatService.getChatById(chatId);
        if (chat == null) {
            return Result.error("-1", "聊天记录不存在");
        }

        // 更新标题
        String title = params.get("title");
        if (title != null && !title.isEmpty()) {
            chat.setTitle(title);
        }

        // 更新其他设置
        String difficulty = params.get("difficulty");
        if (difficulty != null && !difficulty.isEmpty()) {
            chat.setDifficulty(difficulty);
        }

        String keywords = params.get("keywords");
        if (keywords != null) { // 可以为空字符串，表示清除关键词
            chat.setKeywords(keywords);
        }

        // 保存更新
        boolean success = modelChatService.updateById(chat);
        return success ? Result.success() : Result.error("-1", "更新失败");
    }

    /**
     * 删除聊天记录
     * 
     * @param chatId 聊天ID
     * @return 操作结果
     */
    @DeleteMapping("/{chatId}")
    public Result<?> deleteChat(@PathVariable Integer chatId, HttpServletRequest request) {
        String userId = getCurrentUserId(request);

        // 检查聊天是否属于当前用户
        if (!modelChatService.isChatBelongToUser(chatId, userId)) {
            return Result.error("-1", "没有权限操作此聊天记录");
        }

        boolean success = modelChatService.deleteChat(chatId);
        return success ? Result.success() : Result.error("-1", "删除失败");
    }

    /**
     * 获取聊天详情
     * 
     * @param chatId 聊天ID
     * @return 聊天详情
     */
    @GetMapping("/{chatId}")
    public Result<?> getChatDetail(@PathVariable Integer chatId, HttpServletRequest request) {
        String userId = getCurrentUserId(request);

        // 检查聊天是否属于当前用户
        if (!modelChatService.isChatBelongToUser(chatId, userId)) {
            return Result.error("-1", "没有权限访问此聊天记录");
        }

        ModelChat chat = modelChatService.getChatById(chatId);
        if (chat == null) {
            return Result.error("-1", "聊天记录不存在");
        }

        return Result.success(chat);
    }

    /**
     * 获取当前用户ID（实际应用中应该从JWT或session中获取）
     */
    private String getCurrentUserId(HttpServletRequest request) {
        // 这里简单模拟从请求头中获取用户ID
        String userId = request.getHeader("X-User-ID");
        // 临时使用固定用户ID进行开发测试
        return userId != null ? userId : "123456";
    }
}
